package test.app.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import test.app.dto.ContenidoDTO;

public class ContenidoImpl implements test.app.interfaces.Contenido
{
	
	@Override
	public ContenidoDTO getContenido(int id) 
	{
		System.out.println("--- getContenido (JDBC_IMPL) ---");
		Connection con=null;
		PreparedStatement st = null;
		ResultSet rs = null;
		
		try
		{
			Context ctx = new InitialContext();
			DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/HSqlDS");
			con = dataSource.getConnection();
					
			st = con.prepareStatement("Select * from CONTENIDO where ID_CONTENIDO = " + id );
			
			rs = st.executeQuery();
			
			rs.next();

			ContenidoDTO contenidoDTO = new ContenidoDTO(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6));
				
			return contenidoDTO; 
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
		finally
		{
			close(rs);
			close(st);
			close( con );
		}
	}

	@Override
	public Collection getContenidos(char tipo) 
	{
		System.out.println("--- getContenidos (JDBC_IMPL)---");
		List<ContenidoDTO> contenidosDTO = new ArrayList<ContenidoDTO>();
		
		Connection con=null;
		PreparedStatement st = null;
		ResultSet rs = null;
		
		try
		{
			Context ctx = new InitialContext();
			DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/HSqlDS");
			con = dataSource.getConnection();
					
			st = con.prepareStatement("Select * from CONTENIDO where TIPO_CONTENIDO = '" + tipo + "'");
			
			rs = st.executeQuery();
			
			ContenidoDTO contenidoDTO = null;
			while( rs.next() )
			{
				contenidoDTO = new ContenidoDTO(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getString(5),rs.getString(6));
				
				contenidosDTO.add( contenidoDTO );
			}
			
			return contenidosDTO; 
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
			throw new RuntimeException(ex);
		}
		finally
		{
			close(rs);
			close(st);
			close( con );
		}
	}

	private void close(Connection con) {
		if(con != null)
		{
			try 
			{
				con.close();
			} catch (SQLException ex) 
			{
				ex.printStackTrace();
			}
		}
	}

	private void close(PreparedStatement st) {
		if(st != null)
		{
			try 
			{
				st.close();
			} catch (SQLException ex) 
			{
				ex.printStackTrace();
			}
		}
	}

	private void close(ResultSet rs) {
		if(rs != null)
		{
			try 
			{
				rs.close();
			} catch (SQLException ex) 
			{
				ex.printStackTrace();
			}
		}
	}
}
